import 'package:flutter/services.dart';
import 'dart:convert';
import 'ym_flutter_push_platform_interface.dart';

class YmFlutterPush {
  YmFlutterPush._internal();
  static final YmFlutterPush instance = YmFlutterPush._internal();
  factory YmFlutterPush() => instance;

  // 用于接收推送消息的 EventChannel
  final EventChannel eventChannel =
      const EventChannel('ym_flutter_push_message');

  // 获取平台版本
  Future<String?> getPlatformVersion() {
    return YmFlutterPushPlatform.instance.getPlatformVersion();
  }

  // 获取注册信息
  Future<String?> getRegisterInfo() {
    return YmFlutterPushPlatform.instance.getRegisterInfo();
  }

  // 监听推送消息
  Stream<PushMessage> onMessageReceived() {
    return eventChannel.receiveBroadcastStream().map((dynamic event) {
      print('Received push message: $event');
      if (event is String) {
        final Map<String, dynamic> message = json.decode(event);
        return PushMessage.fromJson(message);
      }
      throw FormatException('Invalid message format');
    });
  }
}

// 推送消息模型
class PushMessage {
  final String type;
  final String platform;
  final String title;
  final String description;
  final String payload;
  final bool passThrough;

  PushMessage({
    required this.type,
    required this.platform,
    required this.title,
    required this.description,
    required this.payload,
    required this.passThrough,
  });

  factory PushMessage.fromJson(Map<String, dynamic> json) {
    return PushMessage(
      type: json['type'] as String? ?? '',
      platform: json['platform'] as String? ?? '',
      title: json['title'] as String? ?? '',
      description: json['description'] as String? ?? '',
      payload: json['payload'] as String? ?? '',
      passThrough: json['passThrough'] as bool? ?? false,
    );
  }

  Map<String, dynamic> toJson() => {
        'type': type,
        'platform': platform,
        'title': title,
        'description': description,
        'payload': payload,
        'passThrough': passThrough,
      };

  @override
  String toString() {
    return json.encode(toJson());
  }
}
